package org.elzat.healthboxgatewayapp.security;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elzat.healthboxgatewayapp.credentials.HealthBoxAuthority;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Component
@AllArgsConstructor
@Slf4j
public class HealthBoxAuthenticationManager implements ReactiveAuthenticationManager {

    private final HealthBoxJwt healthBoxJwt;

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        String authToken = authentication.getCredentials().toString();
        log.info("got jwt token: " + authToken);
        return Mono.just(healthBoxJwt.setClaims(authToken))
                .filter(Boolean::valueOf)
                .switchIfEmpty(Mono.empty())
                .map(claims -> {
                    if (healthBoxJwt.isTokenExpired()) {
                        log.info("jwt token has expired");
                        return new UsernamePasswordAuthenticationToken(
                                "",
                                "",
                                Collections.emptyList()
                        );
                    }
                    String userPhone = healthBoxJwt.getUserPhone();
                    log.info("got user phone from jwt token: " + userPhone);
                    List<HealthBoxAuthority> authorities = healthBoxJwt.getAuthorities();
                    log.info("got authorities from jwt token: " + authorities);
                    return new UsernamePasswordAuthenticationToken(
                            userPhone,
                            null,
                            authorities
                    );
                });
    }
}
